enyo.kind({
    name: "enyo.Login",
    kind: enyo.PanelBase,
	
    components: [
		{kind: "PanelContent", headerContent: "Assessment Mobile", submitLeftContent: "Sign In", onSubmitLeft: "doLogin", onHeaderClick: "doHeaderClick", flex: 1, components: [
			{className: "margin-medium", components: [
				{name: "envIndicator", content:""},   // Used to display what environment we are connected to, if this isn't production 
				
				// Status bar displaying various status messages and activity spinner
				{name: "statusBar", kind: "HFlexBox", components: [
					{name: "status", content: $L("Welcome to Assessment Mobile")},
					{kind: "Spacer"},
					{kind: "Spinner", name:"spinner", showing: false}
				]},
				
				// Login dialog displayed on demand. The dialog form elements will be added dynamically into it
				{name: "loginDialog", kind: "ModalDialog", caption: "HP Mobile Login", style: "width: 320px;", lazy: false },
				
				{content: "Please click on \"Sign In\" to login"},
				
				//{ name: "logoutButton", kind: "Button", caption: "Sign Out", className: "enyo-button-negative", onclick: "doLogout" },
				//{ name: "checkAccessButton", kind: "Button", caption: "Check Access",  onclick: "checkAccess" },
				{kind : "Popup", lazy: false, components : [
					{type: "HtmlContent", name: "popupContent", content : "", style: "padding: 20px; text-align: center"},
					{kind: "Button", caption: "OK", onclick: "popupCloseClick", className: "black-bg"}
				]}
			]}
		]},
		
		// Include kind retrieving dynamically the up-to-date definition of HP Mobile Login
		{
			name: "hpMobileLoginSetup",
			kind: "HPMobileLoginSetup",
			onLoginSetupSuccess: "loginSetupSuccess",
			onLoginSetupFailure: "loginSetupFailure"
		},
		// Simple web service checking the access to a protected page
		{
			name: "checkAccess", kind: "HPITWebService",
			method: "GET",
			onSuccess: "accessSuccess",
			onFailure: "accessFailure",
			on401: "accessUnauthorized",
			timeout: 10000 //specified in milliseconds
		}
    ],
	
    create: function () {
		this.log("Entry");
        // calling base class constructor
        this.inherited(arguments);
		//  Display message and spinner while we retrieve definition of HPMobileLogin kind
        this.$.spinner.setShowing(true);
		this.$.status.setContent($L("Setting up login component..."));
		// Call the HPMobileLoginSetup kind to retrieve dynamically the up-to-date definition of HP Mobile Login
		this.$.hpMobileLoginSetup.setup();
		
		// Register global callbacks
	    HPITWebService.registerGlobalResponder({
		    onFailure:function(transport, inResponse){
			    if(inResponse.xhr.status == 401){
                    this.$.status.setContent($L("Authentication failed, please sign-in."));
					this.login(true); // true ==> login component won't check first if user is already connected as we know that he isn't
				}
            }.bind(this),
			onSuccess:function(transport, inResponse){
			    if(inResponse.xhr.status == 0){
                    this.$.status.setContent($L("Unable to connect. Please check your network connection and try again later."));
				}
			}.bind(this)
		})
	},
	
	// Login setup callbacks
	loginSetupSuccess: function () {
		this.log("Login setup retrieved Ok");
		this.$.status.setContent("Checking current session...");
        // Prepare Login Form Dynamically for later
        this.$.loginDialog.createComponents(
            [
			{
				kind: "HPMobileLogin",				// The HP Mobile Login kind displays the user id and password fields and a "Sign In" button
				name: "hpMobileLogin",
				onLoginSuccess: "loginSuccess",		// called on successful login (or if user is signed-in already)
				onLogoutSuccess:"logoutSuccess", 	// called on successful logout
				onLogoutFailure:"logoutFailure", 	// called on failed logout
                onSetupSuccess: "setupSuccess",		// called when the environment we need to connect to is known (i.e. with base SRP URL, environment name...)
                onSetupFailure: "setupFailure"		// called in case of error to setup environment
			},
			{kind: "Button", caption: "Cancel",  onclick: "loginCancelled" } // Add our own "Cancel" button
			],
            {owner: this}
        );
		// Initial setup of HPMobileLogin instance (this will fire onSetupDone when environment definition will be retrieved
        this.$.hpMobileLogin.setup();
	},
	
	loginSetupFailure: function (inSender, errorMsg) {
		this.error("Failed to retrieve Login definition: "+errorMsg);
        this.$.spinner.setShowing(false);
		this.$.status.setContent(errorMsg);
	},
	
	// Login call
	doLogin: function() {
		this.login(false); // false ==> check first if user is already connected. If he is, the user won't be prompted to sign-in.
	},

	login: function(skipSessionCheck) {
		this.$.hpMobileLogin.logInfoBoth("doLogin: skipSessionCheck="+(skipSessionCheck||""));
        this.$.loginDialog.openAtCenter();	// We don't display any message or spinner as the modal login form should be enough for the user experience
		// Call now the Mobile Login (fire onLoginSuccess when done)
        this.$.hpMobileLogin.login(skipSessionCheck);
	},
	
	// Logout call
	doLogout: function() {
        this.$.hpMobileLogin.logInfoBoth("doLogout");
        this.$.status.setContent("Signing out...");
        this.$.spinner.setShowing(true);
        this.$.hpMobileLogin.logout();
		enyo.Data.signout_requested = false;
	},
	
	// Check access call (call protected page)
	/* remove this function, no need this feature
	checkAccess: function() {
        this.$.hpMobileLogin.logInfoBoth("checkAccess");
		if (this.targetURL) {
			this.$.checkAccess.setUrl(this.targetURL);
			this.$.status.setContent("Checking access...");
			this.$.spinner.setShowing(true);
			this.$.checkAccess.call();
		}
	},
	*/
	
	accessSuccess: function(inSender, inResponse, inRequest) {
        this.$.hpMobileLogin.logInfoBoth("checkAccess success");
		this.$.status.setContent("Access Ok");
		this.$.spinner.setShowing(false);
	},
	
	accessFailure: function(inSender, inResponse, inRequest) {
        this.$.hpMobileLogin.logWarnBoth("checkAccess failure with status "+inRequest.xhr.status);
		this.$.status.setContent("Access failed with HTTP Status "+inRequest.xhr.status);
		this.$.spinner.setShowing(false);
	},
	
	accessUnauthorized: function(inSender, inResponse, inRequest) {
        this.$.hpMobileLogin.logWarnBoth("checkAccess failure as user isn't authenticated (HTTP status 401)");
		this.$.status.setContent("Access failed as user isn't authenticated");
		this.$.spinner.setShowing(false);
		// We now let the global responder take care of this by displaying the login form (==> commenting next line)
		// this.login(true); // true ==> login component won't check first if user is already connected as we know that he isn't
	},
	
	// HP Mobile Login callbacks
	loginSuccess: function(inSender, loggedUser){
        this.$.hpMobileLogin.logInfoBoth("loginSuccess");
		this.$.loginDialog.close();
        this.$.status.setContent($L("You are signed in as ")+loggedUser);
		//HPITWebService.resendIfNeeded();
		enyo.Data.current_user = loggedUser;
		this.parentWnd.switchView("home");
    },
	
    logoutSuccess: function() {
        this.$.hpMobileLogin.logInfoBoth("logoutSuccess");
        this.$.spinner.setShowing(false);
        this.$.status.setContent("Signed out");
    },
	
    logoutFailure: function(inSender, errorMsg) {
        this.$.hpMobileLogin.logErrorBoth("logoutFailure: "+errorMsg);
        this.$.spinner.setShowing(false);
        this.$.status.setContent("Sign-out failure: "+errorMsg);
	},
	
	// Called when we have information about what environment we are connected to
    setupSuccess: function(inSender, inSMInstance, lastUser, isSignedIn) {
        this.$.spinner.setShowing(false);
        this.$.hpMobileLogin.logInfoBoth("Entry: env=",inSMInstance.env,", user=",lastUser,", isSignedIn=",isSignedIn);
        var selectedEnv = inSMInstance.env.toUpperCase(); // Environment login is connected to ("dev", "itg" or "prod")
        this.SRPBaseURL = inSMInstance.SRPBaseURL;	// Base URL of the SRP. Use it to build URL to call application specific back-end web services
        this.targetURL = inSMInstance.targetURL;	// Url to a protected page. Can be used to check simply if a user is already authenticated
        if (selectedEnv=="PROD"){
            this.$.envIndicator.setContent("");
            //this.$.appHeader.setStyle("")
        }else{
            this.$.envIndicator.setContent(" - "+selectedEnv);
            //this.$.appHeader.setStyle("color: white; background-color: red;")
        }
		if (isSignedIn && lastUser) {
			this.$.status.setContent($L("You are already signed in as ")+lastUser);
		} else {
			this.$.status.setContent($L("You are not signed in currently"));
		}
		if(isSignedIn == false){
			this.$.hpMobileLogin.logInfoBoth("not signIn");
			this.login(false);
		}else{
			this.$.hpMobileLogin.logInfoBoth("already signIn");
			enyo.Data.current_user = lastUser;
			if(enyo.Data.signout_requested){
				this.doLogout();//this code for debugging
			}else{
				this.parentWnd.switchView("home");
			}
		}
    },
	
    setupFailure: function(inSender, errorMsg) {
        this.$.spinner.setShowing(false);
        this.$.hpMobileLogin.logErrorBoth("setupFailure: "+errorMsg);
        this.$.status.setContent("Setup failure: "+errorMsg);
	},
	
	// Additional Login Cancel button callback
	loginCancelled: function(){
        this.$.hpMobileLogin.logInfoBoth("Entry");
		this.$.loginDialog.close();
        this.$.status.setContent($L("Login was cancelled"));
    },
	popupCloseClick: function() {
		this.$.popup.close();
	}
});